<?php
class RoleController extends ManagerController {
	function RoleController(){
		parent::ManagerController();
	}
	
	public function index(){
		$role_mod = new RoleModel();
		
		$condition = array('site_id' => SITE_ID);
		$this->init_page_info();
		$total = $role_mod->count($condition);
		$this->set_page_total($total);
		
		$roles = $role_mod->find($condition, null, $this->page_info->get_start(), $this->page_info->page_size);
		$this->assign('roles', $roles);
		$this->display();
	}
	
	public function edit(){
		if(IS_POST){
			$this->save();
		}else{
			$acl_mod = new AclModel();
			$acls = $acl_mod->find();
			
			global $site_info;
			if(!empty($this->id)){
				$role_mod = new RoleModel();
				$role = $role_mod->get_by_key_site_limit($this->id);

				ACLHelper::format_acls_checkbox($acls, $role['acl'], $site_info['acl']);
				
				$this->assign('role', $role);
			}else{
				ACLHelper::format_acls_checkbox($acls, null, $site_info['acl']);
			}
			$this->assign('acls', $acls);
			$this->display();
		}
	}
	
	private function save(){
		$name = self::get_post_val('name');
		if(utf8_strlen($name)<2){
			$this->ajax_error('角色名称不能小于2个字符！');
		}
		
		$desc = self::get_post_val('desc');
		
		//权限
		$acl_mod = new AclModel();
		$acls = $acl_mod->find();
		$role_acls = array();
		foreach($acls as $namespace=>$acl_infos){
			if(isset($_POST[$namespace])){
				$role_acls[$namespace] = $_POST[$namespace];
			}
		}
		$acl_array = ACLHelper::parse_acl_array($role_acls);
		$role = array(
			'name' => $name,
			'desc' => $desc,
			'acl' => $acl_array,
			'site_id' => SITE_ID,
		);
		
		$role_mod = new RoleModel();
		if(empty($this->id)){
			//新增
			$role['_id'] = gen_guid();
			$role_mod->insert($role);
			$this->ajax_info('用户角色创建成功！');
		}else{
			//修改
			$role_mod->update_by_key_site_limit($this->id, $role);
			$this->ajax_info('用户角色创建成功！');
		}
	}
	
}

?>